package cc.vv.btpartyjob.partyservice.fragment

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.support.v4.widget.SwipeRefreshLayout
import android.util.Log
import android.view.View
import cc.vv.baselibrary.bean.base.BaseResponseObj
import cc.vv.baselibrary.http.BaseHttpCallBack
import cc.vv.baselibrary.view.BTLoadMoreView
import cc.vv.btpartyjob.jnimodule.binder.BaseBinder
import cc.vv.btpartyjob.partyservice.R
import cc.vv.btpartyjob.partyservice.activity.TinyWishDetailActivity
import cc.vv.btpartyjob.partyservice.adapter.TinyAdapter
import cc.vv.btpartyjob.partyservice.api.PartyServiceAPI
import cc.vv.btpartyjob.partyservice.delegate.TinyFragmentDelegate
import cc.vv.btpartyjob.partyservice.globle.BroadCastServiceKey
import cc.vv.btpartyjob.partyservice.globle.IntentServiceKey
import cc.vv.btpartyjob.partyservice.module.bean.PartyServiceBean
import cc.vv.btpartyjob.partyservice.module.bean.TinyWishBean
import cc.vv.btpartyjob.partyservice.module.resp.TinyWishResponseObj
import cc.vv.btpartyjob.partyservice.server.DataPartyServer
import cc.vv.lkbasecomponent.http.LKHttp
import cc.vv.lkbasecomponent.http.lib.setting.Settings
import cc.vv.lklibrary.http.base.okhttpfactory.plugins.httpplugin.MediaTypeWrap
import cc.vv.mvp.binder.BaseDataBinder
import cc.vv.mvp.fragment.BaseFragmentMVP
import com.chad.library.adapter.base.BaseQuickAdapter

/**
 * 微心愿fragment
 * Created by Chen.qi on 2018/10/27.
 */
class TinyWishFragment : BaseFragmentMVP<TinyFragmentDelegate>()
        , BaseQuickAdapter.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener,
        BaseQuickAdapter.RequestLoadMoreListener {
    /**
     * 适配器
     */
    private var mAdapter: TinyAdapter? = null

    /**
     * 当前页数
     */
    private var pageNo: Int = 1
    /**
     * 每页条数
     */
    private val pageSize: Int = 10
    /**
     * 集合数据
     */
    private var mDataList: ArrayList<TinyWishBean>? = null
    /**
     *
     */
    private var whetherRefresh = false
    /**
     * 刷新数据的广播
     */
    private var mMyBroadCast: MyBroadCast? = null
    /**
     * 刷选器
     */
    private var filter: IntentFilter? = null
    /**
     * 街道id
     */
    private var streetId: String? = null

    /**
     * 社区id
     */
    private var comminitId: String? = null

    /**
     * 网格Id
     */
    private var gridId: String? = null


    /**
     * 初始化广播（接收头像和用户名改变的广播）
     */
    private fun initBroadcast() {
        if (null == mMyBroadCast) {
            mMyBroadCast = MyBroadCast()
            filter = IntentFilter()
            filter?.addAction(BroadCastServiceKey.BROADCAST_REFRESH_OR_FINISH_TINY_WISH)
            context.registerReceiver(mMyBroadCast, filter)
        }
    }


    /**
     * 广播接收
     */
    private inner class MyBroadCast : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent?) {
            //接收头像修改广播，发送对应的消息
            if (intent?.action == BroadCastServiceKey.BROADCAST_REFRESH_OR_FINISH_TINY_WISH) {
                Log.e("lk_chen", "result==" + "收到广播刷新数据");
                pageNo = 1
                DataPartyServer.getTinyWishList(streetId, comminitId, gridId, pageNo, pageSize, true)
            }
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        if (null != mMyBroadCast) {
            context.unregisterReceiver(mMyBroadCast)
        }
    }

    override fun initData() {
        if (mAdapter == null) {
            mDataList = ArrayList()
            mAdapter = TinyAdapter(R.layout.item_tiny_wish)
            viewDelegate?.setRecyclerViewAdapter(mAdapter)
            mAdapter?.setLoadMoreView(BTLoadMoreView())
            viewDelegate?.setAdapterData(mAdapter, mDataList)
            initBroadcast()
        }
    }

    /**
     * query
     */
    fun zuZhiQuery(orgId: String?, type: String?) {
        pageNo = 1
        mDataList?.clear()
        when (type) {
            "0" -> {
                streetId = ""
                comminitId = ""
                gridId = ""
            }
            "1" -> {
                streetId = orgId
                comminitId = ""
                gridId = ""
            }
            "2" -> {
                streetId = ""
                comminitId = orgId
                gridId = ""
            }
            "3" -> {
                streetId = ""
                comminitId = ""
                gridId = orgId
            }
        }
        pageNo = 1
        val serBean = PartyServiceBean()
        serBean.street = streetId
        serBean.community = comminitId
        serBean.grid = gridId
        val path = PartyServiceAPI.tinyWishList + "/" + "$pageNo" + "/" + "$pageSize"
        LKHttp.post(path, serBean, TinyWishResponseObj::class.java,
                object : BaseHttpCallBack<TinyWishResponseObj>() {
                    override fun onSuccess(url: String?, obj: TinyWishResponseObj?) {
                        super.onSuccess(url, obj)
                        if (1 == pageNo) {
                            mDataList?.clear()
                            if (null != obj?.data?.records) {
                                mDataList?.addAll(obj.data.records)
                            }
                            viewDelegate?.setAdapterData(mAdapter, mDataList)
                            mAdapter?.disableLoadMoreIfNotFullPage()
                        }
                    }
                }, true, Settings(MediaTypeWrap.MEDIA_TYPE_RAW_JSON))
    }


    override fun onVisibilityChanged(visible: Boolean) {
        super.onVisibilityChanged(visible)
        if (visible && !whetherRefresh) {
            pageNo = 1
            DataPartyServer.getTinyWishList(streetId, comminitId, gridId, pageNo, pageSize, true)
            whetherRefresh = true
        }
    }

    override fun bindEvenListener() {
        mAdapter?.onItemClickListener = this
        viewDelegate?.bindRefreshListener(this)
        viewDelegate?.bindLoadMore(mAdapter, this)
    }

    override fun getDelegateClass(): Class<TinyFragmentDelegate> {
        return TinyFragmentDelegate::class.java
    }

    override fun getDataBinder(): BaseDataBinder<*, *> {
        return BaseBinder()
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        //微心愿详情
        val intent = Intent()
        intent.putExtra(IntentServiceKey.INTENT_KEY_TINY_DETAIL_ID, mDataList!![position].id)
        intent.setClass(context, TinyWishDetailActivity::class.java)
        startActivity(intent)
    }

    override fun getData(obj: BaseResponseObj<*>?) {
        super.getData(obj)
        if (whetherRefresh) {
            when (obj) {
                is TinyWishResponseObj -> {
                    viewDelegate?.stopRefreshing()
                    if (null == obj.data) {
                        return
                    }
                    if (1 == pageNo) {
                        mDataList?.clear()
                        if (null != obj.data.records) {
                            mDataList!!.addAll(obj.data.records)
                        }
                        viewDelegate?.setAdapterData(mAdapter, mDataList)
                        if (mDataList!!.size < 10) {
                            mAdapter?.loadMoreEnd(true)
                            mAdapter?.loadMoreEnd()
                        }
                        mAdapter?.notifyDataSetChanged()
                    } else {
                        if (mAdapter?.data?.size!! >= obj.data.total) {
                            //数据全部加载完毕
                            mAdapter?.loadMoreEnd(true)
                            mAdapter?.loadMoreEnd()
                        } else {
                            //成功获取更多数据
                            if (null != obj.data.records) {
                                mDataList!!.addAll(obj.data.records)
                            }
                            mAdapter?.setNewData(mDataList)
                            //加载数据
                            mAdapter?.disableLoadMoreIfNotFullPage()
                            mAdapter?.loadMoreComplete()
                        }
                    }
                }
            }
        }
    }

    override fun getBadCode(obj: BaseResponseObj<*>?) {
        super.getBadCode(obj)
        if (1 == pageNo) {
            viewDelegate?.stopRefreshing()
        }
        mAdapter?.loadMoreComplete()
        mAdapter?.loadMoreFail()
    }

    override fun onHttpFailure(url: String?, exceptionStr: String?) {
        super.onHttpFailure(url, exceptionStr)
        if (1 == pageNo) {
            viewDelegate?.stopRefreshing()
        }
    }


    override fun onRefresh() {
        mAdapter?.setEnableLoadMore(false)//这里的作用是防止下拉刷新的时候还可以上拉加载
        pageNo = 1
        DataPartyServer.getTinyWishList(streetId, comminitId, gridId, pageNo, pageSize, false)
    }

    override fun onLoadMoreRequested() {
        if (mDataList!!.size < 10) {
            mAdapter?.loadMoreComplete()
            mAdapter?.loadMoreEnd(true)
            return
        }
        pageNo++
        DataPartyServer.getTinyWishList(streetId, comminitId, gridId, pageNo, pageSize, false)
    }


}